package com.pic4493.net;

import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.SocketTimeoutException;
import java.net.URL;

import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.FileEntity;
import org.apache.http.impl.client.DefaultHttpClient;

import android.util.Log;

public final class HttpAccessor
{
   public final static int MAX_TIMEOUT = 60000;
   public final static int MIN_TIMEOUT = 30000;
   public final static int DEFAULT_TIMEOUT = 60000;
   public static int READ_TIMEOUT = 60000;
   private static HttpURLConnection activeConn;

   public static String sendMessage(String strUrl) throws IOException
   {
	  return sendMessage(strUrl, null);
   }

   public static String sendMessage(String strUrl, byte[] data) throws IOException
   {
	  long startTime = System.currentTimeMillis();
	  try
	  {
		 return sendMessage(strUrl, READ_TIMEOUT, data);
	  }
	  catch (SocketTimeoutException ex)
	  {
		 READ_TIMEOUT = (int) (System.currentTimeMillis() - startTime);
		 if (READ_TIMEOUT > MAX_TIMEOUT)
		 {
			READ_TIMEOUT = MAX_TIMEOUT;
		 }
		 else if (READ_TIMEOUT < MIN_TIMEOUT)
		 {
			READ_TIMEOUT = MIN_TIMEOUT;
		 }
		 throw ex;
	  }
	  catch (IOException ex)
	  {
		 throw ex;
	  }
	  catch (Exception ex)
	  {
		 throw new IOException(ex.getMessage());
	  }
   }

   public static String sendMessage(String strUrl, int timeout) throws IOException
   {
	  return sendMessage(strUrl, timeout, null);
   }

   public static String sendPic(String strUrl, File file)
   {
	  try
	  {
		 HttpPost request = new HttpPost(strUrl);
		 HttpClient httpClient = new DefaultHttpClient();
		 FileEntity entity = new FileEntity(file, "binary/octet-stream");
		 HttpResponse response;

		 request.setEntity(entity);
		 entity.setContentEncoding("binary/octet-stream");
		 response = httpClient.execute(request);

		 // 如果返回状态为200，获得返回的结果
		 if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK)
		 {
			// 图片上传成功
			return response.getEntity().toString();
		 }
	  }
	  catch (Exception e)
	  {
		 Log.d("ERROR", "HttpClient_sendPic(strUrl, File) " + e);
	  }
	  return null;
   }

   public static String sendPic(String strUrl, int timeout, byte[] data) throws IOException
   {
	  StringBuffer buffer = new StringBuffer();
	  HttpURLConnection conn = null;
	  InputStreamReader in = null;
	  OutputStream out = null;
	  String line = "";
	  try
	  {
		 URL url = new URL(strUrl);
		 conn = (HttpURLConnection) url.openConnection();
		 // conn.setRequestProperty("Accept", "text/xml;text/html;*/*");
		 conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
		 conn.setDoInput(true);
		 conn.setDoOutput(true);
		 conn.setDefaultUseCaches(false);
		 conn.setReadTimeout(timeout);
		 activeConn = conn;

		 // �������
		 if (data != null)
		 {
			out = conn.getOutputStream();
			out.write(data);
			out.flush();
		 }

		 in = new InputStreamReader(conn.getInputStream(), "utf-8");
		 BufferedReader rd = new BufferedReader(in);
		 while ((line = rd.readLine()) != null)
		 {
			buffer.append(line);
		 }
		 rd.close();

		 return buffer.toString().trim();
	  }
	  catch (IOException ex)
	  {
		 throw ex;
	  }
	  catch (Exception ex)
	  {
		 throw new IOException(ex.getMessage());
	  }
	  finally
	  {
		 if (out != null)
		 {
			out.close();
			out = null;
		 }

		 if (in != null)
		 {
			in.close();
			in = null;
		 }

		 if (conn != null)
		 {
			conn.disconnect();
			conn = null;
		 }
	  }
   }

   public static String sendMessage(String strUrl, int timeout, byte[] data) throws IOException
   {
	  StringBuffer buffer = new StringBuffer();
	  HttpURLConnection conn = null;
	  InputStreamReader in = null;
	  OutputStream out = null;
	  String line = "";
	  try
	  {
		 URL url = new URL(strUrl);
		 conn = (HttpURLConnection) url.openConnection();
		 conn.setRequestProperty("Accept", "text/xml;text/html;*/*");
		 conn.setRequestProperty("Content-Type", "text/xml;charset=utf-8");
		 conn.setDoInput(true);
		 conn.setDoOutput(true);
		 conn.setDefaultUseCaches(false);
		 conn.setReadTimeout(timeout);
		 activeConn = conn;

		 // �������
		 if (data != null)
		 {
			out = conn.getOutputStream();
			out.write(data);
			out.flush();
		 }

		 in = new InputStreamReader(conn.getInputStream(), "utf-8");
		 BufferedReader rd = new BufferedReader(in);
		 while ((line = rd.readLine()) != null)
		 {
			buffer.append(line);
		 }
		 rd.close();

		 return buffer.toString().trim();
	  }
	  catch (IOException ex)
	  {
		 throw ex;
	  }
	  catch (Exception ex)
	  {
		 throw new IOException(ex.getMessage());
	  }
	  finally
	  {
		 if (out != null)
		 {
			out.close();
			out = null;
		 }

		 if (in != null)
		 {
			in.close();
			in = null;
		 }

		 if (conn != null)
		 {
			conn.disconnect();
			conn = null;
		 }
	  }
   }

   public static void sendVoidMessage(String strUrl) throws IOException
   {
	  try
	  {
		 URL url = new URL(strUrl);
		 HttpURLConnection conn = (HttpURLConnection) url.openConnection();
		 conn.connect();
	  }
	  catch (Exception e)
	  {
		 throw new IOException(e.toString());
	  }
   }

   public static void disconnect()
   {
	  if (activeConn != null)
	  {
		 activeConn.disconnect();
		 activeConn = null;
	  }
   }
}
